package com.lin.utils;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet implements Serializable {

    private static final long serialVersionUID = 1L;

    // 1.重写service方法();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");// 处理响应编码
        request.setCharacterEncoding("UTF-8");
        // 2.获取method参数信息
        String methodName = request.getParameter("method");
        Method method = null;
        try {
            // 3.通过方法名调用反射方法
            method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 4.通过method对象来调用方法
            String result = (String) method.invoke(this, request, response);
            if (result != null && !result.trim().isEmpty()) {
                int index = result.indexOf(":");
                if (index == -1) {
                    request.getRequestDispatcher(result).forward(request, response);
                } else {
                    String start = result.substring(0, index);// 分割出前缀信息
                    String path = result.substring(index + 1);  // 分割出路径信息
                    if ("change".equals(start)) {
                        request.getRequestDispatcher(path).forward(request, response);
                    } else if ("orient".equals(start)) {
                        response.sendRedirect(request.getContextPath() + path);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

}
